package com.aaa.testngdemo;

import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.touch.TouchActions;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.Reporter;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import io.appium.java_client.MobileElement;
import io.appium.java_client.TouchAction;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.AndroidMobileCapabilityType;
import io.appium.java_client.remote.MobileCapabilityType;
import io.appium.java_client.touch.WaitOptions;
import io.appium.java_client.touch.offset.PointOption;
import io.appium.java_client.ws.StringWebSocketClient;

public class SuiteTest {

    private AndroidDriver driver;

    @BeforeSuite
    public void setUp() throws MalformedURLException {
        DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
        desiredCapabilities.setCapability("platformName", "Android");
        desiredCapabilities.setCapability("platformVersion", "10");
        desiredCapabilities.setCapability("devicesName", "R4Q0220622000970");
        desiredCapabilities.setCapability("appPackage", "com.aaa.appiumdemo");
        desiredCapabilities.setCapability("appActivity", "com.aaa.appiumdemo.MainActivity");
        desiredCapabilities.setCapability(MobileCapabilityType.NO_RESET, true);
        desiredCapabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, "uiautomator2");
        // desiredCapabilities.setCapability("unicodeKeyboard", "true");
        // desiredCapabilities.setCapability("resetKeyboard", "true");
        // desiredCapabilities.setCapability("ensureWebviewsHavePages", true);

        URL remoteUrl = new URL("http://localhost:4723/wd/hub");
        driver = new AndroidDriver(remoteUrl, desiredCapabilities);
    }

    @AfterSuite
    public void tearDown() {
        driver.quit();
    }

    @Test
    public void test1() {
        println("点击前");
        MobileElement element = (MobileElement) driver.findElementById("com.aaa.appiumdemo:id/tap");
        element.click();
        println("点击后");

        // 捕获toast
        String searchToast = driver.findElementByXPath("//*[@class='android.widget.Toast']").getText(); // 可以
        println("findElementByXPath=" + searchToast);

        final WebDriverWait wait = new WebDriverWait(driver, 5, 100);
        String toast = "toast的";
        println("开始检查点击事件的toast");
        WebElement toastElement = wait.until(ExpectedConditions.presenceOfElementLocated(findByText(toast))); // 可以
        println("结束检查：" + toastElement.getText());

        // 捕获toast
        searchToast = driver.findElementByXPath("//*[@class='android.widget.Toast']").getText(); // 可以
        println("findElementByXPath=" + searchToast);

        /*
Mon Nov 23 21:25:10 CST 2020  点击前 Thread[main,5,main]
Mon Nov 23 21:25:11 CST 2020  点击后 Thread[main,5,main]
Mon Nov 23 21:25:11 CST 2020  开始检查点击事件的toast Thread[main,5,main]
Mon Nov 23 21:25:12 CST 2020  结束检查：toast的点击 Thread[main,5,main]
        * */


        sleep(3 * 1000);

        println("***********************************************************************************");

        new Thread(() -> {
            println("开始检查长按事件的toast");
            try {
                // WebElement toastElement1 = wait.until(ExpectedConditions.presenceOfElementLocated(findByText(toast)));
                WebElement toastElement1 = wait.until(ExpectedConditions.presenceOfElementLocated(findByClass()));
                println("结束检查1：" + toastElement1.getText());
            } catch (Exception e) {
                println(e.getMessage());
                e.printStackTrace();
            }
            Assert.assertEquals(1, 2);
        }).start();

        sleep(1 * 1000);

        println("长按前");
        element = (MobileElement) driver.findElementById("com.aaa.appiumdemo:id/long_press");
        (new TouchAction(driver))
                // .longPress(PointOption.point(element.getLocation().x, element.getLocation().y))
                .press(PointOption.point(element.getLocation().x, element.getLocation().y))
                .waitAction(WaitOptions.waitOptions(Duration.ofMillis(500)))
                .release()
                .perform();
        println("长按后");

        println("开始检查长按事件的toast");
        try {
            WebElement toastElement1 = wait.until(ExpectedConditions.presenceOfElementLocated(findByText(toast)));
            println("结束检查1：" + toastElement1.getText());
        } catch (Exception e) {
            println(e.getMessage());
            e.printStackTrace();
        }

        /*
2020-11-23 22:32:28.716 1433-2737/? I/WindowManager: addWindow: Window{3c80051 u0 Toast}
2020-11-23 22:32:28.730 11010-11060/io.appium.uiautomator2.server I/appium: method: 'xpath', selector: '//*[@class='android.widget.Toast']', contextId: ''
2020-11-23 22:32:28.737 1433-1490/? I/WindowManager: dispatchResized : win = Window{3c80051 u0 Toast} drawState = HAS_DRAWN
2020-11-23 22:32:28.849 1433-1490/? I/DebugKeepScreenOn: Acquiring screen wakelock due to Window{3c80051 u0 Toast}
2020-11-23 22:32:29.261 11010-11060/io.appium.uiautomator2.server I/appium: Took 1ms to retrieve 1 matches for '//*[@class='android.widget.Toast']' XPath query
2020-11-23 22:32:29.286 11010-11060/io.appium.uiautomator2.server I/appium: Took 0ms to retrieve 1 matches for '//*[@class='android.widget.Toast']' XPath query
2020-11-23 22:32:29.287 11010-11060/io.appium.uiautomator2.server I/appium: Get Text :toast的点击
2020-11-23 22:32:29.287 11010-11060/io.appium.uiautomator2.server I/appium: AppiumResponse: {"sessionId":"8a258bcb-7e59-4440-b8be-99df78d83639","value":"toast的点击"}
=
2020-11-23 22:32:29.313 11010-11060/io.appium.uiautomator2.server I/appium: method: 'xpath', selector: '//*[contains(@text,'toast的')]', contextId: ''
2020-11-23 22:32:29.332 11010-11060/io.appium.uiautomator2.server I/appium: Took 0ms to retrieve 1 matches for '//*[contains(@text,'toast的')]' XPath query
=
2020-11-23 22:32:33.508 11010-11060/io.appium.uiautomator2.server I/appium: method: 'xpath', selector: '//*[@class='android.widget.Toast']', contextId: ''
2020-11-23 22:32:33.554 11010-11060/io.appium.uiautomator2.server I/appium: Took 2ms to retrieve 0 matches for '//*[@class='android.widget.Toast']' XPath query
2020-11-23 22:32:34.040 1433-2969/? I/WindowManager: addWindow: Window{3c80171 u0 Toast}
2020-11-23 22:32:34.086 1433-1490/? I/WindowManager: dispatchResized : win = Window{3c80171 u0 Toast} drawState = HAS_DRAWN
2020-11-23 22:32:34.219 1433-1490/? I/DebugKeepScreenOn: Acquiring screen wakelock due to Window{3c80171 u0 Toast}
2020-11-23 22:32:35.696 11010-11060/io.appium.uiautomator2.server I/appium: method: 'xpath', selector: '//*[@class='android.widget.Toast']', contextId: ''
2020-11-23 22:32:35.771 11010-11060/io.appium.uiautomator2.server I/appium: Took 2ms to retrieve 0 matches for '//*[@class='android.widget.Toast']' XPath query
        */
        /*
2020-11-23 22:22:23.310  开始检查长按事件的toast Thread[Thread-1,5,main]
2020-11-23 22:22:24.310  长按前 Thread[main,5,main]
2020-11-23 22:22:27.030  长按后 Thread[main,5,main]
2020-11-23 22:22:27.030  开始检查长按事件的toast Thread[main,5,main]
=
2020-11-23 22:22:24.729 8831-8889/io.appium.uiautomator2.server I/appium: method: 'xpath', selector: '//*[contains(@text,'toast的')]', contextId: ''
2020-11-23 22:22:24.776 8831-8889/io.appium.uiautomator2.server I/appium: Took 2ms to retrieve 0 matches for '//*[contains(@text,'toast的')]' XPath query
2020-11-23 22:22:25.314 1433-1934/? I/WindowManager: addWindow: Window{384ace1 u0 Toast}
2020-11-23 22:22:25.354 1433-1490/? I/WindowManager: dispatchResized : win = Window{384ace1 u0 Toast} drawState = HAS_DRAWN
2020-11-23 22:22:25.459 1433-1490/? I/DebugKeepScreenOn: Acquiring screen wakelock due to Window{384ace1 u0 Toast}
2020-11-23 22:22:26.951 8831-8889/io.appium.uiautomator2.server I/appium: method: 'xpath', selector: '//*[contains(@text,'toast的')]', contextId: ''
2020-11-23 22:22:27.018 8831-8889/io.appium.uiautomator2.server I/appium: Took 2ms to retrieve 0 matches for '//*[contains(@text,'toast的')]' XPath query
=
2020-11-23 22:22:27.187 8831-8889/io.appium.uiautomator2.server I/appium: Took 2ms to retrieve 0 matches for '//*[contains(@text,'toast的')]' XPath query
2020-11-23 22:22:27.199 8831-8889/io.appium.uiautomator2.server I/appium: method: 'xpath', selector: '//*[contains(@text,'toast的')]', contextId: ''
2020-11-23 22:22:27.305 740-830/? W/BufferQueueProducer: [Toast#0]:1368: disconnect: not connected (req=1)
2020-11-23 22:22:27.306 1433-27237/? I/WindowManager: removeIfPossible: Window{384ace1 u0 Toast} callers=com.android.server.wm.WindowState.removeIfPossible:1368384 com.android.server.wm.WindowManagerService.removeWindow:1389328 android.view.IWindowSession$Stub.onTransact:3561532 com.android.server.wm.Session.onTransact:4759696 android.os.Binder.execTransactInternal:5522272
2020-11-23 22:22:27.307 1433-27237/? I/WindowManager: Not removing Window{384ace1 u0 Toast EXITING} due to exit animation
2020-11-23 22:22:27.316 1433-2737/? W/NotificationService: Toast already killed. pkg=com.aaa.appiumdemo callback=android.app.ITransientNotification$Stub$Proxy@3f5c97d
2020-11-23 22:22:27.428 1433-1490/? I/WindowManager: Exit animation finished in Window{384ace1 u0 Toast EXITING}: remove=true
2020-11-23 22:22:27.454 1433-1490/? I/WindowManager: postWindowRemoveCleanupLocked: Window{384ace1 u0 Toast}
2020-11-23 22:22:27.454 1433-1490/? I/WindowManager: Removing Window{384ace1 u0 Toast} from WindowToken{3c45153 android.os.Binder@40cb8b1}
2020-11-23 22:22:27.738 8831-8889/io.appium.uiautomator2.server I/appium: Took 2ms to retrieve 0 matches for '//*[contains(@text,'toast的')]' XPath query
2020-11-23 22:22:27.754 8831-8889/io.appium.uiautomator2.server I/appium: method: 'xpath', selector: '//*[contains(@text,'toast的')]', contextId: ''
        * */
    }

    public By findByText(String text) {
        return By.xpath("//*[contains(@text,'" + text + "')]");
    }

    public By findByClass() {
        return By.xpath("//*[@class='android.widget.Toast']");
    }

    public void sleep(long millsecond) {
        try {
            Thread.sleep(millsecond);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void println(String msg) {
        println("", msg);
    }

    SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

    public void println(String tag, String msg) {
        String result = new StringBuilder()
                .append(mSimpleDateFormat.format(new Date()))
                .append(" ")
                .append(tag)
                .append(" ")
                .append(msg)
                .append(" ")
                .append(Thread.currentThread())
                .toString();
        System.out.println(result);
        Reporter.log(result);
    }
}
